package com.drinks.yiniang.ui.activity.user.order;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.user.order.OrderDetailAdapter;
import com.drinks.yiniang.common.recycler.decoration.OrderDetailItemDecoration;
import com.drinks.yiniang.common.help.PayManager;
import com.drinks.yiniang.entity.common.StringJson;
import com.drinks.yiniang.entity.common.StringMsgJson;
import com.drinks.yiniang.entity.event.OrderEvent;
import com.drinks.yiniang.entity.event.PayWXEventBus;
import com.drinks.yiniang.entity.goods.GoodsJson;
import com.drinks.yiniang.entity.goods.RecommendGoodsJson;
import com.drinks.yiniang.entity.pay.AliPayJson;
import com.drinks.yiniang.entity.pay.WeiXinPayJson;
import com.drinks.yiniang.entity.user.address.DeliverAddressJson;
import com.drinks.yiniang.entity.user.order.OrderDetailJson;
import com.drinks.yiniang.io.api.GoodsApiIO;
import com.drinks.yiniang.io.api.OrderApiIO;
import com.drinks.yiniang.io.api.ShoppingCartApiIO;
import com.drinks.yiniang.ui.activity.goods.GoodsDetailsActivity;
import com.drinks.yiniang.ui.widget.dialog.ContactServiceDialog;
import com.drinks.yiniang.ui.widget.dialog.PayDialog;
import com.drinks.yiniang.ui.widget.layout.OrderDetailHeaderLayout;
import com.drinks.yiniang.ui.widget.recycler.BaseRecyclerView;
import com.drinks.yiniang.utils.AddressUtils;
import com.drinks.yiniang.utils.RecyclerUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.entity.BaseJson;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.listener.OnSureCancelListener;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.listener.OnNavgationBarClickListener;
import com.hansen.library.ui.widget.dialog.Material2Dialog;
import com.hansen.library.ui.widget.layout.BorderLinearLayout;
import com.hansen.library.ui.widget.nav.NavigationBarLayout;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import static com.drinks.yiniang.entity.user.order.OrderDetailJson.ITEM_TYPE_ORDER_DETAIL_ADDRESS;
import static com.drinks.yiniang.entity.user.order.OrderDetailJson.ITEM_TYPE_ORDER_DETAIL_LOGISTICS;
import static com.drinks.yiniang.entity.user.order.OrderDetailJson.ITEM_TYPE_ORDER_DETAIL_LIST;
import static com.drinks.yiniang.entity.user.order.OrderDetailJson.ITEM_TYPE_ORDER_DETAIL_TOTAL;
import static com.drinks.yiniang.entity.user.order.OrderDetailJson.ITEM_TYPE_ORDER_DETAIL_DELIVERY;
import static com.drinks.yiniang.entity.user.order.OrderDetailJson.ITEM_TYPE_ORDER_DETAIL_RECOMMEND_TITLE;
import static com.drinks.yiniang.entity.user.order.OrderDetailJson.ITEM_TYPE_ORDER_DETAIL_RECOMMEND;
import static com.hansen.library.Constants.TYPE_ORDER_ALREADY_DELIVERED;
import static com.hansen.library.Constants.TYPE_ORDER_ALREADY_EVALUATE;
import static com.hansen.library.Constants.TYPE_ORDER_ALREADY_REFUND;
import static com.hansen.library.Constants.TYPE_ORDER_CANCEL;
import static com.hansen.library.Constants.TYPE_ORDER_PLATEFORM_CANCEL;
import static com.hansen.library.Constants.TYPE_ORDER_REFUNDIND;
import static com.hansen.library.Constants.TYPE_ORDER_REFUND_REFUSE;
import static com.hansen.library.Constants.TYPE_ORDER_SELFT_GET;
import static com.hansen.library.Constants.TYPE_ORDER_WAIT_FOR_DELIVER;
import static com.hansen.library.Constants.TYPE_ORDER_WAIT_FOR_EVALUATE;
import static com.hansen.library.Constants.TYPE_ORDER_WAIT_FOR_PAY;
import static com.hansen.library.Constants.TYPE_ORDER_WAIT_FOR_RECEIPT;

/**
 * 订单详情页面
 *
 * @author han
 * @date 2019/09/06
 */
public class OrderDetailsActivity extends BaseTranBarActivity implements OnNavgationBarClickListener,
        BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener, OnSureCancelListener,
        PayDialog.OnPayListener, PayManager.PayResultListener {

    private final int REQ_ORDER_EVALUATE_CODE = 0x01;

    private final int TYPE_CONFIRM_DIALOG_DELETE = 0x0A;//删除订单确认
    private final int TYPE_CONFIRM_DIALOG_CANCEL = 0x0B;//取消订单
    private final int TYPE_CONFIRM_DIALOG_RECEIPT = 0x0C;//确认收货

    //nav
    private NavigationBarLayout nav_bar_order_details;
    private BaseRecyclerView rcv_order_details;
    private BorderLinearLayout ll_order_detail_bottom;
    //删除订单
    private Button btn_order_detail_delete;
    //取消订单
    private Button btn_order_detail_cancel;
    //支付或评价
    private Button btn_order_detail_sure;

    private OrderDetailHeaderLayout mHeaderView;

    private OrderDetailAdapter mOrderDetailAdapter;

    private PayManager mPayManager;

    //订单状态(查询订单详情的时候，待支付订单查询详情需要传支付status值)
    private String mOrderPayStatus;
    //订单类型, -1全部 0待支付 1已支付 2已发货 3已送达 4交易完成 5已评价 6已取消 7退款仲裁（退款中） 9门店自提 10已退款 11拒绝退款 12缺货取消一品脱订单状态
    private String mOrderType;
    //订单编号
    private String mOrderNo;
    //订单id
    private String mOrderId;

    @Override
    protected void initView() {
        nav_bar_order_details = findViewById(R.id.nav_bar_order_details);

        rcv_order_details = findViewById(R.id.rcv_order_details);

        ll_order_detail_bottom = findViewById(R.id.ll_order_detail_bottom);

        btn_order_detail_delete = findViewById(R.id.btn_order_detail_delete);
        btn_order_detail_cancel = findViewById(R.id.btn_order_detail_cancel);
        btn_order_detail_sure = findViewById(R.id.btn_order_detail_sure);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mContext = this;

        mOrderId = getIntent() != null ? getIntent().getStringExtra(Constants.KeyOrderId) : null;
        mOrderPayStatus = getIntent() != null ? getIntent().getStringExtra(Constants.KeyStatus) : null;
        mOrderPayStatus = Constants.TYPE_ORDER_WAIT_FOR_PAY.equals(mOrderPayStatus) ? "0" : "1";

        initAdapter();

        getOrderDetail();
    }

    private void initAdapter() {
        mOrderDetailAdapter = new OrderDetailAdapter(mContext, new ArrayList<OrderDetailJson.OrderDetailList>());
        mOrderDetailAdapter.addHeaderView(getHeaderView());
        mOrderDetailAdapter.setHeaderAndEmpty(true);
        mOrderDetailAdapter.setCommonEmpty(getLayoutInflater(), rcv_order_details);
        mOrderDetailAdapter.bindToRecyclerView(rcv_order_details);

        rcv_order_details.setLayoutManager(RecyclerUtils.getOrderDetailGridLayout(mContext, mOrderDetailAdapter.getData()));
        rcv_order_details.addItemDecoration(OrderDetailItemDecoration.getItemDPDecoration(10));
    }

    //获取header
    private View getHeaderView() {
        mHeaderView = new OrderDetailHeaderLayout(mContext);

        return mHeaderView;
    }

    @Override
    protected void initListener() {
        nav_bar_order_details.setOnNavgationBarClickListener(this);
        btn_order_detail_delete.setOnClickListener(this);
        btn_order_detail_cancel.setOnClickListener(this);
        btn_order_detail_sure.setOnClickListener(this);

        mOrderDetailAdapter.setOnItemClickListener(this);
        mOrderDetailAdapter.setOnItemChildClickListener(this);

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.btn_order_detail_delete://删除订单
                doDeleteButtonClick();
                break;
            case R.id.btn_order_detail_cancel://提醒发货
                doCancelButtonClick();
                break;
            case R.id.btn_order_detail_sure://支付或评价或确认收货
                doPayButtonClick();
                break;
            default:
                break;
        }
    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_order_details;
    }

    @Override
    public void onBackClick(View v) {
        finish();
    }

    @Override
    public void onEditClick(View v) {//客服
        ContactServiceDialog dialog = ContactServiceDialog.newInstance();

        dialog.show(getSupportFragmentManager(), Constants.TAG_CONTACT_SERVICE_DIALOG);
    }

    @Override
    public void onPaySuccess(String msg) {
        doPaySuccess();
    }

    @Override
    public void onPayFail(String errCode, String errMsg) {
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(PayWXEventBus event) {
        if (PayWXEventBus.PAY_STATUS_SUCCESS == event.getPayStatus()) {//支付成功
            if (PayManager.PAY_TYPE_ORDER_DETAIL_PAY.equals(event.getPayPage())) {
                doPaySuccess();
            }
        }
    }

    @Override
    public void onPayClick(int payType) {
        if (mPayManager == null) {
            mPayManager = new PayManager(this);
            mPayManager.setPayResultListener(this);
        }
        switch (payType) {
            case PayManager.PAY_CHANNEL_ALIPAY://支付宝支付
                doPayByAliPay();
                break;
            case PayManager.PAY_CHANNEL_WX://微信支付
                doPayByWeiXinPay();
                break;
            case PayManager.PAY_CHANNEL_WALLET://钱包支付
                doPayByWalletPay();
                break;
            default:
                break;
        }
    }

    @Override
    public void onPayDismiss() {
    }

    @Override
    public void onPayClose() {

    }

    @Override
    public void onSure(int type, String value) {
        switch (type) {
            case TYPE_CONFIRM_DIALOG_CANCEL://取消
                doOrderCancel();
                break;
            case TYPE_CONFIRM_DIALOG_DELETE://删除
                doOrderDelete();
                break;
            case TYPE_CONFIRM_DIALOG_RECEIPT://确认收货
                doOrderConfirm();
                break;
            default:
                break;
        }
    }

    @Override
    public void onCancel(int type) {
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        Intent mIntent;

        OrderDetailJson.OrderDetailList goodsData = mOrderDetailAdapter.getItem(position);

        if (goodsData == null) return;

        switch (adapter.getItemViewType(position + adapter.getHeaderLayoutCount())) {
            case ITEM_TYPE_ORDER_DETAIL_RECOMMEND://推荐商品
                mIntent = new Intent(mContext, GoodsDetailsActivity.class);
                mIntent.putExtra(Constants.KeyGoodsId, goodsData.getGoods_id());
                startActivity(mIntent);
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        Intent mIntent;

        OrderDetailJson.OrderDetailList goodsData = mOrderDetailAdapter.getItem(position);

        if (goodsData == null)  return;

        switch (adapter.getItemViewType(position + adapter.getHeaderLayoutCount())) {
            case ITEM_TYPE_ORDER_DETAIL_ADDRESS://地址
                break;
            case ITEM_TYPE_ORDER_DETAIL_LOGISTICS://物流信息
                break;
            case ITEM_TYPE_ORDER_DETAIL_LIST://商品
                if (view.getId() == R.id.tv_order_detail_return) {
                    mIntent = new Intent(mContext, RefundSubmitActivity.class);
                    mIntent.putExtra(Constants.KeyGoodsId, goodsData.getGoods_id());
                    mIntent.putExtra(Constants.KeyOrderNo, mOrderNo);
                    startActivity(mIntent);
                }
                break;
            case ITEM_TYPE_ORDER_DETAIL_TOTAL://总计
                break;
            case ITEM_TYPE_ORDER_DETAIL_DELIVERY://配送信息
                if (view.getId() == R.id.tv_order_detail_delivery_all) {
                }
                break;
            case ITEM_TYPE_ORDER_DETAIL_RECOMMEND://推荐
                if(view.getId() == R.id.iv_home_goods_add_cart) addToCart(goodsData.getGoods_id());
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == Constants.RESULT_CODE_NORMAL && requestCode == REQ_ORDER_EVALUATE_CODE) {
            EventBus.getDefault().post(new OrderEvent(OrderEvent.REFRESH_ALL_AND_WAIT_EVALUATE_ORDER));
            getOrderDetail();
        }
    }

    private void doPaySuccess() {
        setResult(Constants.RESULT_CODE_NORMAL);
        finish();
    }

    private void initConfirmDialog(int type, String content) {
        Material2Dialog dialog = Material2Dialog.newInstance(type, content);

        dialog.show(getSupportFragmentManager(), Constants.TAG_TIPS_DIALOG);
    }

    //支付按钮订单不同状态下的不同点击事件，支付或评价或确认收货
    private void doPayButtonClick() {
        if (StringUtils.isEmpty(mOrderType) || StringUtils.isEmpty(mOrderId)) return;

        switch (mOrderType) {
            case TYPE_ORDER_WAIT_FOR_PAY://待支付(支付操作)
                PayDialog dialog = PayDialog.newInstance();
                dialog.show(getSupportFragmentManager(), Constants.TAG_PAY_DIALOG);
                break;
            case TYPE_ORDER_WAIT_FOR_RECEIPT://待收货(确认收货操作)
            case TYPE_ORDER_ALREADY_DELIVERED://已送达
                initConfirmDialog(TYPE_CONFIRM_DIALOG_RECEIPT, getString(R.string.text_receipt_confirm_mark));
                break;
            case TYPE_ORDER_WAIT_FOR_EVALUATE://交易完成-待评价(订单评价)
                Intent intent = new Intent(mContext, OrderEvaluateActivity.class);
                intent.putExtra(Constants.KeyOrderId, mOrderId);
                startActivityForResult(intent, REQ_ORDER_EVALUATE_CODE);
                break;
            case TYPE_ORDER_WAIT_FOR_DELIVER://已支付
            case TYPE_ORDER_ALREADY_EVALUATE://已评价-交易成功
            case TYPE_ORDER_CANCEL://已取消
            case TYPE_ORDER_REFUNDIND://退款中
            case TYPE_ORDER_SELFT_GET://门店自提
            case TYPE_ORDER_ALREADY_REFUND://已退款
            case TYPE_ORDER_REFUND_REFUSE://拒绝退款
            case TYPE_ORDER_PLATEFORM_CANCEL://平台取消
            default:
                break;
        }
    }

    //取消按钮订单不同状态下的不同点击事件
    private void doCancelButtonClick() {
        if (StringUtils.isEmpty(mOrderType) || StringUtils.isEmpty(mOrderId)) return;

        switch (mOrderType) {
            case TYPE_ORDER_WAIT_FOR_PAY://待支付(取消订单操作)
                initConfirmDialog(TYPE_CONFIRM_DIALOG_CANCEL, getString(R.string.text_order_cancel_mark));
                break;
            case TYPE_ORDER_WAIT_FOR_DELIVER://已支付(提醒发货)
                doOrderRemindDeliver();
                break;
            case TYPE_ORDER_WAIT_FOR_EVALUATE://交易完成-待评价(晒单)
            case TYPE_ORDER_ALREADY_EVALUATE://已评价-交易成功(晒单)
                ToastUtils.showShort("晒单");
                break;
            case TYPE_ORDER_CANCEL://已取消
            case TYPE_ORDER_REFUNDIND://退款中
            case TYPE_ORDER_SELFT_GET://门店自提
            case TYPE_ORDER_ALREADY_REFUND://已退款
            case TYPE_ORDER_REFUND_REFUSE://拒绝退款
            case TYPE_ORDER_PLATEFORM_CANCEL://平台取消
            default:
                break;
        }
    }

    //删除按钮订单不同状态下的不同点击事件
    private void doDeleteButtonClick() {
        if (StringUtils.isEmpty(mOrderType) || StringUtils.isEmpty(mOrderId)) return;

        switch (mOrderType) {
            case TYPE_ORDER_ALREADY_EVALUATE://已评价-交易成功
            case TYPE_ORDER_CANCEL://已取消
            case TYPE_ORDER_ALREADY_REFUND://已退款
            case TYPE_ORDER_REFUND_REFUSE://拒绝退款
            case TYPE_ORDER_PLATEFORM_CANCEL://平台取消
                initConfirmDialog(TYPE_CONFIRM_DIALOG_DELETE, getString(R.string.text_order_delete_mark));
                break;
            case TYPE_ORDER_WAIT_FOR_PAY://待支付
            case TYPE_ORDER_WAIT_FOR_DELIVER://已支付
            case TYPE_ORDER_WAIT_FOR_RECEIPT://待收货
            case TYPE_ORDER_ALREADY_DELIVERED://已送达
            case TYPE_ORDER_WAIT_FOR_EVALUATE://交易完成-待评价
            case TYPE_ORDER_REFUNDIND://退款中
            case TYPE_ORDER_SELFT_GET://门店自提
                break;
            default:
                break;
        }
    }

    //订单取消
    private void doOrderCancel() {
        if (StringUtils.isEmpty(mOrderId)) {
            ToastUtils.showShort(R.string.text_the_order_not_exist);
            return;
        }

        showLoadingDialog();

        OrderApiIO.getInstance().doOrderCancel(mOrderId, new APIRequestCallback<BaseJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(BaseJson res) {
                EventBus.getDefault().post(new OrderEvent(OrderEvent.REFRESH_ALL_AND_WAIT_PAY_ORDER));
                finish();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //订单删除(只有全部订单进入才能删除)
    private void doOrderDelete() {
        if (StringUtils.isEmpty(mOrderId)) {
            ToastUtils.showShort(R.string.text_the_order_not_exist);
            return;
        }

        showLoadingDialog();

        OrderApiIO.getInstance().doOrderDelete(mOrderId, new APIRequestCallback<StringJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(StringJson res) {
                EventBus.getDefault().post(new OrderEvent(OrderEvent.REFRESH_ALL_ORDER));
                finish();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //订单确认
    private void doOrderConfirm() {
        if (StringUtils.isEmpty(mOrderId)) {
            ToastUtils.showShort(R.string.text_the_order_not_exist);
            return;
        }

        showLoadingDialog();

        OrderApiIO.getInstance().doOrderConfirm(mOrderId, new APIRequestCallback<BaseJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(BaseJson res) {
                EventBus.getDefault().post(new OrderEvent(OrderEvent.REFRESH_ALL_AND_WAIT_RECEIVED_EVALUATE_ORDER));
                getOrderDetail();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //提醒发货
    private void doOrderRemindDeliver() {
        showLoadingDialog();

        OrderApiIO.getInstance().doOrderRemindDeliver(mOrderId, new APIRequestCallback<StringMsgJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(StringMsgJson res) {
                ToastUtils.showShort(res.getData().getMsg());
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //支付宝支付
    private void doPayByAliPay() {
        if (StringUtils.isEmpty(mOrderNo)) {
            ToastUtils.showShort(R.string.text_the_order_not_exist);
            return;
        }

        showLoadingDialog();

        OrderApiIO.getInstance().doPayByAliPay(mOrderNo, new APIRequestCallback<AliPayJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(AliPayJson res) {
                mPayManager.slingAiPay(res.getData());
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //微信支付
    private void doPayByWeiXinPay() {
        if (StringUtils.isEmpty(mOrderNo)) {
            ToastUtils.showShort(R.string.text_the_order_not_exist);
            return;
        }

        showLoadingDialog();

        OrderApiIO.getInstance().doPayByWeiXin(mOrderNo, new APIRequestCallback<WeiXinPayJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(WeiXinPayJson res) {
                mPayManager.slingWXPay(res.getData(), PayManager.PAY_TYPE_ORDER_DETAIL_PAY);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //钱包支付
    private void doPayByWalletPay() {
        if (StringUtils.isEmpty(mOrderNo)) {
            ToastUtils.showShort(R.string.text_the_order_not_exist);
            return;
        }

        showLoadingDialog();

        OrderApiIO.getInstance().doPayByWallet(mOrderNo, new APIRequestCallback<AliPayJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(AliPayJson res) {
                doPaySuccess();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //获取订单详情
    private void getOrderDetail() {
        if (StringUtils.isEmpty(mOrderId)) {
            ToastUtils.showShort(getString(R.string.text_the_order_not_exist));
            return;
        }

        showLoadingDialog();

        OrderApiIO.getInstance().getOrderDetail(mOrderId, mOrderPayStatus, new APIRequestCallback<OrderDetailJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(OrderDetailJson res) {
                if (mOrderDetailAdapter == null) {
                    return;
                }
                //设置订单数据
                setOrderData(res.getData());
                //获取推荐商品
                getRecommend();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //获取推荐列表
    private void getRecommend() {
        GoodsApiIO.getInstance().getRecommendGoodsList(new APIRequestCallback<RecommendGoodsJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(RecommendGoodsJson res) {
                if (mOrderDetailAdapter == null) {
                    return;
                }

                addRecommendGoods(res.getData());
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    //设置订单数据
    private void setOrderData(OrderDetailJson.OrderDetailData orderData) {
        //订单状态 0待支付 1已支付 2已发货 3已送达 4交易完成 5已评价 6已取消 7退款仲裁（退款中）8 moes里的状态 9门店自提 10已退款 11拒绝退款 12缺货取消一品脱订单状态
        if (orderData.getStatus() == null) {
            orderData.setStatus("");
        }

        mOrderNo = orderData.getOrder_no();

        mOrderType = orderData.getStatus() == null ? "" : orderData.getStatus();

        mOrderDetailAdapter.getData().clear();
        mOrderDetailAdapter.setShowRefund("1".equals(mOrderType) || "2".equals(mOrderType)
                || "3".equals(mOrderType) || "4".equals(mOrderType) || "5".equals(mOrderType));

        switch (mOrderType) {
            case TYPE_ORDER_WAIT_FOR_PAY://待支付(显示取消订单, 支付)
                mHeaderView.addTwoChildView();
                mHeaderView.setIconImage(R.mipmap.icon_24hour_close);
                mHeaderView.setStatusText(R.string.text_order_auto_close_24_hours);

                setIsShowBottomLayout(true);
                setButtonData(false, true, true, 0, R.string.text_order_cancel, R.string.text_pay);
                break;
            case TYPE_ORDER_WAIT_FOR_DELIVER://已支付(显示提醒发货)(配货中)
                mHeaderView.addTwoChildView();
                mHeaderView.setIconImage(R.mipmap.icon_in_distribution);
                mHeaderView.setStatusText(R.string.text_already_pay_and_delivering);

                setIsShowBottomLayout(true);
                setButtonData(false, true, false, 0, R.string.text_remind_deliver, 0);
                break;
            case TYPE_ORDER_WAIT_FOR_RECEIPT://待收货(显示确认收货)(显示配送中)
                mHeaderView.addFourChildView();
                if(Constants.TYPE_DELIVER_WAY_SELF_GET.equals(orderData.getSelf_get())) {//是自提
                    mHeaderView.setShopAddress(StringUtils.getNullEmptyConvert__(orderData.getStores_address()));
                    mHeaderView.setUserAddress(StringUtils.getNullEmptyConvert__(orderData.getStores_address()));
                } else {
                    DeliverAddressJson.DeliverAddressData addressData = orderData.getAddress();

                    if(addressData == null) {
                        addressData = new DeliverAddressJson.DeliverAddressData();
                    }

                    StringBuilder builder = new StringBuilder(AddressUtils.getDeliverAddress(addressData.getRegion_province(), addressData.getRegion_city(), addressData.getRegion_district()));
                    builder.append(StringUtils.getNoNullString(addressData.getAddress()));

                    mHeaderView.setShopAddress(StringUtils.getNullEmptyConvert__(orderData.getStores_address()));
                    mHeaderView.setUserAddress(builder.toString());
                }

                setIsShowBottomLayout(true);
                setButtonData(false, false, true, 0, 0, R.string.text_receipt_confirm);
                break;
            case TYPE_ORDER_ALREADY_DELIVERED://已送达
                mHeaderView.addTwoChildView();
                mHeaderView.setIconImage(R.mipmap.icon_in_distribution);
                mHeaderView.setStatusText(R.string.text_already_delivered);

                setIsShowBottomLayout(true);
                setButtonData(false, false, true, 0, 0, R.string.text_receipt_confirm);
                break;
            case TYPE_ORDER_WAIT_FOR_EVALUATE://交易完成-待评价(显示评价, 晒单)
                mHeaderView.addTwoChildView();
                mHeaderView.setIconImage(R.mipmap.icon_already_signed);
                mHeaderView.setStatusText(R.string.text_order_already_signed);

                setIsShowBottomLayout(true);
                setButtonData(false, true, true, 0, R.string.text_order_share, R.string.text_evaluate);
                break;
            case TYPE_ORDER_ALREADY_EVALUATE://已评价-交易成功(显示删除, 晒单)
                mHeaderView.addTwoChildView();
                mHeaderView.setIconImage(R.mipmap.icon_already_signed);
                mHeaderView.setStatusText(R.string.text_order_already_evaluate);

                setIsShowBottomLayout(true);
                setButtonData(true, true, false, R.string.text_order_delete, R.string.text_order_share, 0);
                break;
            case TYPE_ORDER_CANCEL://已取消(显示删除订单)
                mHeaderView.addTwoChildView();
                mHeaderView.setIconImage(R.mipmap.icon_in_distribution);
                mHeaderView.setStatusText(R.string.text_already_cancel);

                setIsShowBottomLayout(true);
                setButtonData(true, false, false, R.string.text_order_delete, 0, 0);
                break;
            case TYPE_ORDER_REFUNDIND://退款中
                mHeaderView.addTwoChildView();
                mHeaderView.setIconImage(R.mipmap.icon_in_distribution);
                mHeaderView.setStatusText(R.string.text_refunding);

                setIsShowBottomLayout(false);
                setButtonData(false, false, false,0, 0, 0);
                break;
            case TYPE_ORDER_SELFT_GET://门店自提
                mHeaderView.addTwoChildView();
                mHeaderView.setIconImage(R.mipmap.icon_in_distribution);
                mHeaderView.setStatusText(R.string.text_shop_yourself);

                setIsShowBottomLayout(false);
                setButtonData(false, false, false,0, 0, 0);
                break;
            case TYPE_ORDER_ALREADY_REFUND://已退款(显示删除订单)
                mHeaderView.addTwoChildView();
                mHeaderView.setIconImage(R.mipmap.icon_in_distribution);
                mHeaderView.setStatusText(R.string.text_already_refund);

                setIsShowBottomLayout(true);
                setButtonData(true, false, false, R.string.text_order_delete, 0, 0);
                break;
            case TYPE_ORDER_REFUND_REFUSE://拒绝退款(显示删除订单)
                mHeaderView.addTwoChildView();
                mHeaderView.setIconImage(R.mipmap.icon_in_distribution);
                mHeaderView.setStatusText(R.string.text_refuse_refund);

                setIsShowBottomLayout(true);
                setButtonData(true, false, false, R.string.text_order_delete, 0, 0);
                break;
            case TYPE_ORDER_PLATEFORM_CANCEL://平台取消(显示删除订单)
                mHeaderView.addTwoChildView();
                mHeaderView.setIconImage(R.mipmap.icon_in_distribution);
                mHeaderView.setStatusText(R.string.text_already_cancel_by_platform);

                setIsShowBottomLayout(true);
                setButtonData(true, false, false, R.string.text_order_delete, 0, 0);
                break;
            default:
                mHeaderView.addTwoChildView();
                mHeaderView.setIconImage(R.mipmap.icon_in_distribution);
                mHeaderView.setStatusText(R.string.text_order_status_exception);

                setIsShowBottomLayout(false);
                setButtonData(false, false, false,0, 0, 0);
                break;
        }


        if (orderData.getExpress() == null) {
            addAddress(orderData);
        } else {
            addDeliverProgress(orderData);
        }

        mOrderDetailAdapter.addData(orderData.getGoods());
        //订单总计
        addOrderTotal(orderData);
        //配送进度
        if (orderData.getExpress() != null) {
            addLogistics(orderData);
        }
    }

    private void setIsShowBottomLayout(boolean isShow) {
        FrameLayout.LayoutParams paramsBottom = (FrameLayout.LayoutParams) rcv_order_details.getLayoutParams();

        if(isShow) {
            paramsBottom.bottomMargin = getResources().getDimensionPixelOffset(R.dimen.height_bottom_layout);
            ll_order_detail_bottom.setVisibility(View.VISIBLE);
        } else {
            paramsBottom.bottomMargin = 0;
            ll_order_detail_bottom.setVisibility(View.GONE);
        }
    }

    private void setButtonData(boolean showDelete, boolean showCancel, boolean showSure, @StringRes int deleteId, @StringRes int cancelId, @StringRes int sureId) {
        btn_order_detail_delete.setVisibility(showDelete ? View.VISIBLE : View.GONE);
        btn_order_detail_cancel.setVisibility(showCancel ? View.VISIBLE : View.GONE);
        btn_order_detail_sure.setVisibility(showSure ? View.VISIBLE : View.GONE);

        if(showDelete) btn_order_detail_delete.setText(deleteId);
        if(showCancel) btn_order_detail_cancel.setText(cancelId);
        if(showSure) btn_order_detail_sure.setText(sureId);
    }

    //订单状态 0待支付 1已支付 2已发货 3已送达 4交易完成 5已评价 6已取消 7退款仲裁（退款中）8 moes里的状态 9门店自提 10已退款 11拒绝退款 12缺货取消一品脱订单状态
    //添加收货地址(未支付，已支付未发货，已取消，平台取消)
    private void addAddress(OrderDetailJson.OrderDetailData orderData) {
        OrderDetailJson.OrderDetailList data = new OrderDetailJson.OrderDetailList();
        data.setItemType(ITEM_TYPE_ORDER_DETAIL_ADDRESS);
        try {
            data.setTempOrderData((OrderDetailJson.OrderDetailData) orderData.clone());
            mOrderDetailAdapter.addData(data);
        } catch (CloneNotSupportedException e) {
        }
    }

    //添加物流信息(已发货，已送达，已完成，已评价)
    private void addDeliverProgress(@NonNull OrderDetailJson.OrderDetailData orderData) {
        OrderDetailJson.OrderDetailList data = new OrderDetailJson.OrderDetailList();
        data.setItemType(ITEM_TYPE_ORDER_DETAIL_DELIVERY);
        try {
            data.setTempOrderData((OrderDetailJson.OrderDetailData) orderData.clone());
            mOrderDetailAdapter.addData(data);
        } catch (CloneNotSupportedException e) {
        }
    }

    //添加订单总计
    private void addOrderTotal(OrderDetailJson.OrderDetailData orderData) {
        OrderDetailJson.OrderDetailList data = new OrderDetailJson.OrderDetailList();
        data.setItemType(ITEM_TYPE_ORDER_DETAIL_TOTAL);
        try {
            data.setTempOrderData((OrderDetailJson.OrderDetailData) orderData.clone());
            mOrderDetailAdapter.addData(data);
        } catch (CloneNotSupportedException e) {
        }
    }

    //添加配送进度(已发货，已送达，已完成，已评价)
    private void addLogistics(OrderDetailJson.OrderDetailData orderData) {
        OrderDetailJson.OrderDetailList data = new OrderDetailJson.OrderDetailList();
        data.setItemType(ITEM_TYPE_ORDER_DETAIL_LOGISTICS);
        try {
            data.setTempOrderData((OrderDetailJson.OrderDetailData) orderData.clone());
            mOrderDetailAdapter.addData(data);
        } catch (CloneNotSupportedException e) {
        }
    }

    //添加推荐商品
    private void addRecommendGoods(List<GoodsJson.GoodsList> lst) {
        if (CommonUtils.isEmptyList(lst)) {
            return;
        }

        //添加标题
        OrderDetailJson.OrderDetailList titleData = new OrderDetailJson.OrderDetailList();
        titleData.setItemType(ITEM_TYPE_ORDER_DETAIL_RECOMMEND_TITLE);
        mOrderDetailAdapter.addData(titleData);

        OrderDetailJson.OrderDetailList data;
        GoodsJson.GoodsList goodsData;

        for (int i = 0; i < lst.size(); i++) {
            goodsData = lst.get(i);

            data = new OrderDetailJson.OrderDetailList();
            data.setItemType(ITEM_TYPE_ORDER_DETAIL_RECOMMEND);
            data.setGoods_name(goodsData.getName());
            data.setGoods_id(goodsData.getId());
            data.setCover_url(goodsData.getCover_url());
            data.setRecommend_reason(goodsData.getRecommend_reason());
            data.setGoods_price(goodsData.getApp_price());

            mOrderDetailAdapter.addData(data);
        }
    }

    private void addToCart(String goodsId) {
        showLoadingDialog();

        ShoppingCartApiIO.getInstance().addToShopCart(goodsId, new APIRequestCallback<BaseJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(BaseJson res) {
                ToastUtils.showShort(getString(R.string.text_add_success));
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        if (mPayManager != null) {
            mPayManager.destroyPayRegister();
        }
        super.onDestroy();
    }
}
